<template>
    <div class="page">
        <div class="table" v-show="showTableList">
            <div class="crumbs">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item><i class="el-icon-menu"></i> 文章管理</el-breadcrumb-item>
                    <el-breadcrumb-item>文章列表</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <!--工具条-->
            <el-col :span="24" class="toolbar">
                <el-form :inline="true">
                    <el-form-item>
                        <el-input v-model.trim="like.value" placeholder="请输入文章名称" clearable></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" v-on:click="getList">查询</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" v-on:click="add">添加新文章</el-button>
                    </el-form-item>
                    <!--<el-form-item>
                        <el-select v-model="filters[0].value" placeholder="请选择文章状态" @change="getList">
                          <el-option label="有效" :value="1"></el-option>
                          <el-option label="无效" :value="0"></el-option>
                        </el-select>
                    </el-form-item>-->
                </el-form>
            </el-col>

            <el-table :data="tableData" height="660" border style="width: 100%" :header-cell-style="{'background':'#eef1f6','color':'#1f2d3d'}">
                <template v-for="item in headObj">
                    <template v-if="item.fixed">
                        <el-table-column :prop="item.prop" :key="item.prop" :label="item.label" fixed align="center" :min-width="item.width" :formatter="timeFormatter"></el-table-column>
                    </template>
                    <template v-else>
                        <el-table-column :prop="item.prop" :key="item.prop" :label="item.label" align="center" :min-width="item.width" :formatter="timeFormatter"></el-table-column>
                    </template>
                </template>
				<el-table-column align="center" label="文章状态">
					<template slot-scope="scope">
						<el-tag size="small" :type="formatClass(scope.row.status)">{{ formatStatu(scope.row.status) }}</el-tag>
					</template>
				</el-table-column>
                <el-table-column label="操作" width="220" align="center" class-name="tableOperate">
                    <template slot-scope="scope">
                        <el-button @click="handleCompileClick(scope.$index, scope.row)" type="text" size="small" :disabled="scope.row.status === 0 || scope.row.isChange">编译</el-button>
                     	<el-button @click="handleCompileClick(scope.$index, scope.row, true)" type="text" size="small" :disabled="scope.row.status === 0 || scope.row.isChange">强制编译</el-button>
                        <el-button @click="handleEditClick(scope.$index, scope.row)" type="text" size="small" :disabled="scope.row.status === 0 || scope.row.isChange">编辑</el-button>
                        <!--<el-button @click="handleDeleteClick(scope.$index, scope.row)" v-if="filters[0].value == 1" type="text" size="small">无效</el-button>-->
                        <el-button v-if="scope.row.status === 1" @click="handleDeleteClick(scope.row)" type="text" size="small">失效</el-button>
                        <el-button v-else @click="handleAddClick(scope.row)" type="text" size="small">生效</el-button>
                     	<!-- <el-button @click="handleTestClick(scope.$index, scope.row)" type="text" size="small" v-if="filters[0].value == 1">测试编译</el-button> -->
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
            	 	background
                  	@size-change="handleSizeChange"
                  	@current-change="handleCurrentChange"
                  	:current-page="currentPage"
                  	:page-sizes="[10, 20, 30, 50, 100]"
                  	:page-size="pageNumb"
                  	layout="sizes, prev, pager, next"
                  	:total="totalNum">
                </el-pagination>
            </div>
        </div>
        <AddArticle :id="selectId" v-if="showDialog" @closedialog="closeDialog" @refresh="getList"></AddArticle>
        <ArticleTest :id="selectId" v-if="showDialog2" @closedialog="closeDialog2"></ArticleTest>
        <!-- <addPhrase :id="selectId" v-if="showDialog" @closedialog="closeDialog" @refresh="getList"></addPhrase> -->
        <!-- <DeleteConfirm :data="deleteConfirmObj.data" v-if="deleteConfirmObj.showDeleteConfirmDialog" @close="closeDeleteConfirmDialog" @refresh="getList"></DeleteConfirm> -->
    </div>
</template>

<script>
import NProgress from "nprogress";
import api from "../../api/api";
import util from "../../common/util";
import AddArticle from "./article/AddArticle.vue";
import ArticleTest from "./article/ArticleTest.vue";
import typeOptions from '../../common/typeOptions';

const channelOptions = [
    {
      label: "灯塔文章",
      value: 1
    },
    {
      label: "银河文章",
      value: 2
    },
    {
      label: "中信建投",
      value: 3
    }  
]
export default {
  data() {
    return {
      headObj: [],
      selectId: null,
      filters: [
        {
          type: "1",
          key: "status",
          value: ''
        }
      ],
      like: {
        key: "name",
        value: ""
      },
      showTableList: true,
      //添加或者编辑原子
      showDialog: false,
      showDialog2: false,
      currentPage: 1,
      pageNumb: 30,
      totalNum: 0,
      listLoading: false,
      tableData: []
    };
  },
  components: {
    AddArticle,
    ArticleTest
  },
  methods: {
    closeDialog() {
      this.showDialog = false;
    },
    closeDialog2() {
      this.showDialog2 = false;
    },
    timeFormatter(row, column) {
      switch (column.property) {
        case "update_time":
          return util.formatDate.format(
            new Date(row[column.property]),
            "yyyy-MM-dd hh:mm:ss"
          );
        case "create_time":
          return util.formatDate.format(
            new Date(row[column.property]),
            "yyyy-MM-dd hh:mm:ss"
          );
        case "category":
          let str = '';
          for (let index = 0; index < typeOptions.length; index++) {
            if (row[column.property] == typeOptions[index].value) {
              str = typeOptions[index].label;
              break;
            }
          }
          return str;
        case "channel":
          let str1 = '';
          if (row[column.property]) {
            
            var channels = row[column.property].split(',');
            for (let index = 0; index < channelOptions.length; index++) {
              if (channels.indexOf(channelOptions[index].value) > -1 || channels.indexOf(channelOptions[index].value.toString()) > -1) {
                str1 += channelOptions[index].label + ',';
              }
            }
            str1 = str1.substring(0, str1.length - 1);
          }
          return str1;
        default:
          return row[column.property];
          break;
      }
    },
    handleSizeChange(val) {
      	this.pageNumb = val
      	this.getList()
    },
    handleCurrentChange(val) {
      	this.currentPage = val
      	this.getList()
    },
	formatClass(data) {
		switch(data) {
			case 0:
				return 'danger'
			case 1:
				return ''
		}
	},
	formatStatu(data) {
		switch(data) {
			case 0:
				return '无效'
			case 1:
				return '有效'
		}
	},
    add() {
      	this.selectId = null
      	this.showDialog = true
    },
    //获取原子列表
    getList() {
      	let para = {
	        currentPage: this.currentPage - 1,
	        pageNumb: this.pageNumb,
	        wheres: JSON.stringify(this.filters),
	        like: JSON.stringify(this.like),
	        order: "id",
	        tableName: "article"
      	}
      	this.listLoading = true
      	NProgress.start()
      	let that = this
      	api.getList(para).then(res => {
          	if (res.ret == 0) {
	            that.totalNum = res.data.totleNumb
              that.tableData = res.data.dataList;
              // 异动文章id列表
              var changeList = [33,34,35,36,37,38,43,44,45];
	            that.tableData.forEach(item => {
	              	item.isChange = changeList.indexOf(item.id) !== -1 ? true : false;
	            })
	            that.listLoading = false
	            NProgress.done()
          	}
       	}).catch(e => {
           that.$message({ type: "error", message: "获取文章列表失败,请刷新重试" })
        })
    },
    handleEditClick(index, row) {
      	this.selectId = row.id;
      	this.showDialog = true;
    },
    handleCompileClick(index, row, force) {
  		this.$confirm(`此操作将编译该文章, 是否继续?`, "提示", {
	        confirmButtonText: "确定",
	        cancelButtonText: "取消",
	        type: "warning"
      	}).then(() => {
	      	let id = row.id;
	      	let options = {
	            tableName: "article",
	            id: id
	      	}
	      	if (force) {
	            options.force = force;
	      	}
	      	api.compile(options).then(res => {
              	if (res.ret == 0) {
	                this.$message({ type: "success", message: "编译操作已发出，请稍等生成相关新闻文章" })
              	} else if(res.ret == -1) {
              		this.$message({ type: "warning", message: res.data })
            	} else if(res.ret == -2) {
            		this.$message({ type: "error", message: "请登录之后操作！" })
            	}
            })
       	}).catch(() => {
          	this.$message({ type: "info", message: "已取消操作" });
    	})
    },
    handleTestClick(index, row) {
      	this.selectId = row.id;
      	this.showDialog2 = true;
    },
	handleDeleteClick(row) {
      this.$confirm("此操作将失效该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
          let id = row.id;
          api.delete({
              tableName: "article",
              id: id
            }).then(res => {
              if (res.ret == 0) {
                this.$message({ type: "success", message: "失效成功!" })
                this.getList()
              } else if(res.ret == -1) {
	              	this.$message({ type: "error", message: res.data.sqlMessage });
	            } else if(res.ret == -2) {
	              	this.$message({ type: "error", message: '请登录之后操作！' });
	            }
            })
        }).catch(() => {
          this.$message({ type: "info", message: "已取消失效" })
        })
    },
    handleAddClick(row) {
      	this.$confirm("此操作将生效该记录, 是否继续?", "提示", {
        	confirmButtonText: "确定",
        	cancelButtonText: "取消",
        	type: "warning"
      	}).then(() => {
        	api.addBack({
            	tableName: "article",
            	id: row.id
	     	}).then(res => {
	            if (res.ret == 0) {
	              	this.$message({ type: "success", message: "生效成功!" })
	              	this.getList()
	            } else if(res.ret == -1) {
	              	this.$message({ type: "error", message: res.data.sqlMessage });
	            } else if(res.ret == -2) {
	              	this.$message({ type: "error", message: '请登录之后操作！' });
	            }
	      	})
      	}).catch(() => {
          	this.$message({ type: 'info', message: '已取消生效' });          
    	})
    }
//  handleDeleteClick(index, row) {
//    	let str = "失效";
//    	if (row.status == 0) {
//      	str = "生效"
//    	}
//    	this.$confirm(`此操作将${str}该记录, 是否继续?`, "提示", {
//      	confirmButtonText: "确定",
//      	cancelButtonText: "取消",
//      	type: "warning"
//    	}).then(() => {
//        	let id = row.id;
//        	if (row.status != 0) {
//          	api.delete({
//	                tableName: "article",
//	                id: id
//           	}).then(res => {
//	                if (res.ret == 0) {
//	                  	this.$message({ type: "success", message: "操作成功!" })
//	                  	this.getList()
//	                } else {
//	              		this.$message({ type: "error", message: "请登录之后操作！" })
//	            	}	
//            	})
//        	} else {
//	            let form = Object.assign(row, {});
//	            form.status = 1;
//	            delete form.statusStr;
//	            api.addOrEditSubmit({
//	                tableName: "article",
//	                form: form
//	  			}).then(res => {
//	                if (res.ret == 0) {
//	                  	this.$message({ type: "success", message: "操作成功!" })
//	                  	this.getList();
//	                }
//	          	})
//        	}
//      }).catch(() => {
//        	this.$message({ type: "info", message: `已取消${str}` })
//      })
//  }
  },
  mounted() {
    this.headObj = [
	  	{
	        prop: "id",
	        label: "id",
	        width: "80",
	        fixed: false
	  	},
      	{
	        prop: "name",
	        label: "文章名称",
	        width: "200",
	        fixed: false
      	},
      	{
	        prop: "category",
	        label: "文章标的",
	        width: "200",
	        fixed: false
      	},
      	{
	        prop: "create_time",
	        label: "添加时间",
	        width: "150",
	        fixed: false
      	},
      	{
	        prop: "update_time",
	        label: "更新时间",
	        width: "150",
	        fixed: false
      	}
    ]
    this.getList()
  }
};
</script>
<style type="text/css">
	.tableOperate .cell {
		display: flex;
		justify-content: space-around;
	}
</style>
